﻿Imports System.Data
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.OleDb
Imports System
Imports System.Globalization

Partial Class Interfaz_frmAdminRequisicion
    Inherits System.Web.UI.Page
    Dim CL As New Logica.ModuloAdministracion.ControladorLogica
    Dim dtDatos As New DataTable
    Dim dataset As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CL = Logica.ModuloAdministracion.ControladorLogica.getInstance
        If CL.visibilidadesFormsInternos("Administracion", Session("user").ToString) = False Then
            Response.Redirect("Index.aspx")
        End If

        'se guardan datos en secion para el positback de la pagina respecto al los datos del datagridview
        If Session("Requisicion") Is Nothing Then
            Session("Requisicion") = dtDatos
        Else
            dtDatos = DirectCast(Session("Requisicion"), DataTable)
        End If

        If Not Page.IsPostBack Then
            cargarControlesIniciales()
            CargarDDL()

            Try
                dtDatos.Columns.Add(New DataColumn("ITEM"))
                dtDatos.Columns.Add(New DataColumn("UNIDAD"))
                dtDatos.Columns.Add(New DataColumn("DETALLE"))
                dtDatos.Columns.Add(New DataColumn("CANTIDAD"))
                dtDatos.Columns.Add(New DataColumn("PRECIOUNITARIO"))
                dtDatos.Columns.Add(New DataColumn("CODMATERIAL"))
                dtDatos.Columns.Add(New DataColumn("PROVEEDOR"))

                Me.GridRequisicion.DataBind()
                Me.GridRequisicion.DataSource = Me.dtDatos

            Catch
            End Try
        End If
        ' Me.GridRequisicion.DataBind()
        Me.GridRequisicion.DataSource = Me.dtDatos
    End Sub

#Region "Funcionalidades"
    Private Sub CargarDDL()
        Try
            Dim i As Integer
            Dim ArrayProveedor As New ArrayList
            Dim ArrayFamilia As New ArrayList
            Dim ArrayMaterial As New ArrayList
            ArrayProveedor = CL.ObtenerProveedor()
            ArrayFamilia = CL.ObtenerFamilia()
            ArrayMaterial = CL.ObtenerMaterial()

            If Not Page.IsPostBack Then
                For i = 0 To ArrayProveedor.Count - 1
                    Dim item As New ListItem
                    item.Text = DirectCast(ArrayProveedor.Item(i), Proveedor).Rznsocial
                    item.Value = DirectCast(ArrayProveedor.Item(i), Proveedor).Rut
                    Me.DropProveedor.Items.Add(item)
                Next

                Me.DropFamilias.Items.Add("Seleccione Familia")
                For i = 0 To ArrayFamilia.Count - 1
                    Dim itemFamilia As New ListItem

                    itemFamilia.Text = DirectCast(ArrayFamilia.Item(i), Familia).Nombre
                    itemFamilia.Value = DirectCast(ArrayFamilia.Item(i), Familia).Id
                    Me.DropFamilias.Items.Add(itemFamilia)
                Next

                For i = 0 To ArrayMaterial.Count - 1
                    Dim itemMateriales As New ListItem
                    itemMateriales.Value = DirectCast(ArrayMaterial.Item(i), Material).ID
                    itemMateriales.Text = DirectCast(ArrayMaterial.Item(i), Material).Nombre

                    Me.DropCodigoMateriales.Items.Add(itemMateriales)
                Next
            End If
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub

    Public Sub Mensaje(ByVal msg As String)
        Dim alertScript As String = "<script language=JavaScript runat=server>"
        alertScript &= "alert('" & msg & "');"
        alertScript &= "</script>"
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "clientScrip", alertScript)
    End Sub

    Private Sub InsertarRequisicion()
        Try
            Dim drDatos As DataRow = dtDatos.NewRow

            If Me.TxtUnidad.Text <> "" And Me.TxtDescripcion.Text <> _
            "" And Me.TxtCantidad.Text <> "" And Me.TxtUM.Text <> "" _
            And Me.TxtPrecioUnit.Text <> "" Then

                drDatos.Item("ITEM") = Me.DropMaterial.Text
                drDatos.Item("UNIDAD") = Me.TxtUnidad.Text
                drDatos.Item("DETALLE") = Me.TxtDescripcion.Text
                drDatos.Item("CANTIDAD") = Me.TxtCantidad.Text
                drDatos.Item("PRECIOUNITARIO") = CInt(Me.TxtPrecioUnit.Text)
                drDatos.Item("CODMATERIAL") = Me.DropMaterial.SelectedValue
                drDatos.Item("PROVEEDOR") = Me.DropProveedor.SelectedValue

                dtDatos.Rows.Add(drDatos)

                Me.GridRequisicion.DataSource = dtDatos
                Me.GridRequisicion.DataBind()

                Me.LimpiarItem()
                Me.GridRequisicion.ForeColor = Drawing.Color.Blue
                Me.LabelAviso.Text = "Los datos han sido ingresados satisfactoriamente"
            Else
                Me.LabelAviso.ForeColor = Drawing.Color.Red
                Me.LabelAviso.Text = "Complete todos los datos"
            End If

        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub

    Private Sub LimpiarItem()
        TxtUM.Text = String.Empty
        TxtPrecioUnit.Text = String.Empty
        TxtCantidad.Text = String.Empty
        TxtDescripcion.Text = String.Empty
        Me.TxtUnidad.Text = String.Empty
    End Sub

    Private Sub IngresarRequisicionBD()
        Try
            Dim filaGrid As GridViewRow

            'Datos Fijos
            Dim proveedor As Proveedor = DirectCast(CL.ObtenerProveedorRut(DropProveedor.SelectedValue).Item(0), Proveedor)
            Dim Fecha As String = Me.TxtFecha.Text
            Dim dia As String = Fecha.Substring(0, 2)
            Dim mes As String = Fecha.Substring(3, 2)
            Dim año As String = Fecha.Substring(6, 4)

            'Declaraciones para item de la requisicion
            Dim ReqItem As String
            Dim ReqUnidad As String
            Dim ReqDetalle As String
            Dim ReqCantidad As String
            Dim ReqPrecioUnitario As String
            Dim ReqCodigo As String
            Dim ReqProveedor As String
            Dim TotalPorItem As Integer
            Dim TotalNeto As Integer
            Dim iva As Integer
            Dim totalBruto As Integer
            Dim cantidad As Integer

            'Declaraciones para insert a BD
            Dim ArrayItemRequisicion As New ArrayList

            'Suma Valores de actividades
            With Me.GridRequisicion
                ' Recorrer las filas del dataGridView  
                For fila As Integer = 0 To .Rows.Count - 1
                    filaGrid = Me.GridRequisicion.Rows(fila)

                    'Recorrer la cantidad de columnas que contiene el dataGridView  
                    ReqItem = filaGrid.Cells(1).Text
                    ReqUnidad = filaGrid.Cells(2).Text
                    ReqDetalle = filaGrid.Cells(3).Text
                    ReqCantidad = filaGrid.Cells(4).Text
                    ReqPrecioUnitario = filaGrid.Cells(5).Text
                    ReqCodigo = filaGrid.Cells(6).Text
                    ReqProveedor = DirectCast(CL.ObtenerProveedorRut(filaGrid.Cells(7).Text).Item(0), Proveedor).Rut

                    TotalPorItem = CInt(filaGrid.Cells(4).Text) * CInt(filaGrid.Cells(5).Text)
                    TotalNeto = TotalNeto + TotalPorItem
                    cantidad = cantidad + ReqCantidad

                    Dim itemRequisicion As New Item(ReqCodigo, ReqDetalle, ReqCantidad, ReqPrecioUnitario, _
                                                ReqItem, TotalPorItem * 0.19, TotalPorItem)
                    itemRequisicion.FKPROVEEDOR = ReqProveedor
                    ArrayItemRequisicion.Add(itemRequisicion)
                Next fila
            End With


            'Calculo Valores Neto - Bruto - Iva
            iva = TotalNeto * 0.19
            totalBruto = TotalNeto + iva

            'Creacion factura e Ingreso a la BD
            Dim Prioridad As String = ""

            If Me.CkProg3.Checked = True Then
                Prioridad = "Alta (1-2 Dias)"
            Else
                If Me.CkProg2.Checked = True Then
                    Prioridad = "Programada (" + TxTProgramada.Text + ")"
                Else
                    If Me.CkProg.Checked = True Then
                        Prioridad = "Normal (1 semana)"
                    End If
                End If
            End If

            Dim nuevaRequisicion As New Requisicion(0, Prioridad, TxtUnidad.Text, TotalNeto, cantidad, TxtUM.Text, Me.TxtDescripcion.Text)
            nuevaRequisicion.ArrayItem = ArrayItemRequisicion

            CL.insertarRequisicion(nuevaRequisicion)
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try

    End Sub

    Private Sub vaciaGrid()
        Try
            dtDatos = DirectCast(Session("Requisicion"), DataTable)
            If Not dtDatos Is Nothing Then
                dtDatos.Clear()
                Session("Requisicion") = dtDatos
            End If
            Me.GridRequisicion.DataSource = Nothing
            Me.GridRequisicion.DataBind()
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub

    Public Sub BuscarItemFamilia()
        Try
            Dim arrayMaterial As ArrayList = CL.ObtenerMaterialFamilia(Me.DropFamilias.SelectedValue)

            DropMaterial.Enabled = True

            Me.DropMaterial.Items.Clear()
            If arrayMaterial.Count <> 0 Then
                For i As Integer = 0 To arrayMaterial.Count - 1
                    Dim item As Material = DirectCast(arrayMaterial.Item(i), Material)
                    Dim itemMate As New ListItem
                    itemMate.Text = DirectCast(arrayMaterial.Item(i), Material).Nombre
                    itemMate.Value = DirectCast(arrayMaterial.Item(i), Material).Codigo
                    Me.DropMaterial.Items.Add(itemMate)

                Next
            Else
                Me.Mensaje("No hay materiales asociados a la familia seleccionada")
            End If
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub
#End Region

#Region "Botones"

    Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
        Me.LimpiarItem()
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        InsertarRequisicion()
    End Sub

    Protected Sub BtnValidar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnValidar.Click
        IngresarRequisicionBD()
        Me.vaciaGrid()
    End Sub
#End Region

#Region "Eventos Grid"
    'Grid Material
    Protected Sub GridRequisicion_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        GridRequisicion.PageIndex = e.NewPageIndex
        'Bind data to the GridView control.
        GridRequisicion.DataSource = Session("Requisicion")
        GridRequisicion.DataBind()
    End Sub

    Protected Sub GridRequisicion_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        'Set the edit index.
        GridRequisicion.EditIndex = e.NewEditIndex
        'Bind data to the GridView control.
        GridRequisicion.DataSource = Session("Requisicion")
        GridRequisicion.DataBind()
    End Sub

    Protected Sub GridRequisicion_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        'Reset the edit index.
        GridRequisicion.EditIndex = -1
        'Bind data to the GridView control.
        GridRequisicion.DataSource = Session("Requisicion")
        GridRequisicion.DataBind()
    End Sub

    Protected Sub GridRequisicion_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        'Retrieve the table from the session object.
        Dim dt As DataTable = CType(Session("Requisicion"), DataTable)

        'Update the values.
        Dim row As GridViewRow = GridRequisicion.Rows(e.RowIndex)
        'Dim actividad As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text.ToString
        Dim CODIGO As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text
        Dim DETALLE As String = (CType((row.Cells(3).Controls(0)), TextBox)).Text
        Dim CANTIDAD As String = (CType((row.Cells(4).Controls(0)), TextBox)).Text
        Dim PRECIOUNITARIO As String = (CType((row.Cells(5).Controls(0)), TextBox)).Text

        'dt.Rows(row.DataItemIndex)("ITEM") = actividad
        dt.Rows(row.DataItemIndex)("CODIGO") = CODIGO
        dt.Rows(row.DataItemIndex)("DETALLE") = DETALLE
        dt.Rows(row.DataItemIndex)("CANTIDAD") = CANTIDAD
        dt.Rows(row.DataItemIndex)("PRECIOUNITARIO") = PRECIOUNITARIO

        'Reset the edit index.
        GridRequisicion.EditIndex = -1

        'Bind data to the GridView control.
        GridRequisicion.DataSource = Session("Requisicion")
        GridRequisicion.DataBind()
    End Sub

    Sub GridRequisicion_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Dim dt As DataTable = CType(Session("Requisicion"), DataTable)
        dt.Rows(e.RowIndex).Delete()
        GridRequisicion.DataSource = dt
        GridRequisicion.DataBind()
    End Sub
#End Region

#Region "Eventos"
    Protected Sub CheckCodigo_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckCodigo.CheckedChanged

        If Me.CheckCodigo.Checked = True Then
            Me.DropFamilias.Enabled = False
            Me.DropCodigoMateriales.Enabled = True
            Me.CheckFamilia.Checked = False
        Else
            Me.DropFamilias.Enabled = True
            Me.DropCodigoMateriales.Enabled = False
        End If

    End Sub

    Protected Sub CheckFamilia_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckFamilia.CheckedChanged
        If Me.CheckFamilia.Checked = True Then
            Me.DropCodigoMateriales.Enabled = False
            Me.DropFamilias.Enabled = True
            Me.CheckCodigo.Checked = False

            Me.DropMaterial.Visible = True
            Me.LblMaterial.Visible = True
            Me.lblDosptosMaterial.Visible = True
        Else
            Me.DropFamilias.Enabled = True
            Me.DropCodigoMateriales.Enabled = False

            Me.DropMaterial.Visible = False
            Me.LblMaterial.Visible = False
            Me.lblDosptosMaterial.Visible = False
        End If
    End Sub

    Protected Sub DropFamilias_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropFamilias.SelectedIndexChanged
        BuscarItemFamilia()
    End Sub

    Protected Sub CkProg2_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CkProg2.CheckedChanged
        If CkProg2.Checked Then
            TxTProgramada.Visible = True
        Else
            TxTProgramada.Visible = False
        End If
    End Sub
#End Region

#Region "Utilidades"
    Private Sub cargarControlesIniciales()
        LblMaterial.Visible = False
        lblDosptosMaterial.Visible = False
        DropMaterial.Visible = False
        TxTProgramada.Visible = False
        DropCodigoMateriales.Enabled = False
        DropFamilias.Enabled = False
        DropMaterial.Enabled = False
    End Sub
#End Region

   
   
End Class
